﻿using BarcodeStandard;
using log4net;
using Org.BouncyCastle.Asn1.Cmp;
using SkiaSharp;
using StoreProject.BLL;
using StoreProject.BLL.SettingBLL;
using StoreProject.DAL;
using StoreProject.Entity;
using StoreProject.Entity.OtherEntity;
using StoreProject.Forms.SettingForms;
using StoreProject.OtherUtil;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace StoreProject.Forms
{
    public partial class PrintBoxNumForm : Form
    {
        ILog _log = LogManager.GetLogger("PrintBoxNumForm");
        IniConfig iniConfig = null;

        OrderBLL _orderBll = new OrderBLL();
        LineTypeBLL lineTypeBLL = new LineTypeBLL();
        OperatorBLL operatorBLL = new OperatorBLL();
        ChangefulBLL changefulBLL = new ChangefulBLL();
        BoxNumBLL boxNumBLL = new BoxNumBLL();


        public PrintBoxNumForm()
        {
            InitializeComponent();
            int oneBoxCount = Convert.ToInt32(numOneBoxCount.Value);
            int boxCount = Convert.ToInt32((int)numBoxCount.Value);
            this.txtAllBoxCount.Text = (oneBoxCount * boxCount).ToString();
        }

        private void numOneBoxCount_ValueChanged(object sender, EventArgs e)
        {
            int oneBoxCount = Convert.ToInt32(numOneBoxCount.Value);
            int boxCount = Convert.ToInt32((int)numBoxCount.Value);
            this.txtAllBoxCount.Text = (oneBoxCount * boxCount).ToString();
        }

        private void numBoxCount_ValueChanged(object sender, EventArgs e)
        {
            Computer();
        }

        private void Computer()
        {
            boxnum = initboxnum;
            int oneBoxCount = Convert.ToInt32(numOneBoxCount.Value);
            int boxCount = Convert.ToInt32((int)numBoxCount.Value);
            this.txtAllBoxCount.Text = (oneBoxCount * boxCount).ToString();

            if (boxCount == 1)
            {
                boxnum = boxnum + boxCount - 1;
                this.txtBoxNum.Text = DateTime.Now.Year.ToString() +  initboxnum.ToString();
            }
            else
            {
                boxnum = boxnum + boxCount - 1;
                this.txtBoxNum.Text = DateTime.Now.Year.ToString() + initboxnum + "至" + DateTime.Now.Year + boxnum;
            }
            
            //boxnum = initboxnum;
        }

        int boxnum = 0;
        int initboxnum = 0;
        private void PrintBoxNumForm_Load(object sender, EventArgs e)
        {
            iniConfig = new IniConfig("printer_config.ini");
            #region 下拉框初始化
            cmbLineType.DisplayMember = "LineTypeName";
            cmbLineType.ValueMember = "LineTypeName";
            cmbOperator.DisplayMember = "OperatorName";
            cmbOperator.ValueMember = "OperatorName";
            //线型数据源配置
            var linetype = lineTypeBLL.GetList().ToList();
            cmbLineType.DataSource = linetype;
            //操作员数据源配置
            var operatorEx = operatorBLL.GetList().ToList();
            cmbOperator.DataSource = operatorEx;
            #endregion

            var changeEntity = changefulBLL.GetList().ToList();
            if (changeEntity != null && changeEntity.Count == 1)
            {
                initboxnum = changeEntity[0].BoxNum + 1;
                boxnum = initboxnum;
                this.txtBoxNum.Text = DateTime.Now.Year + boxnum.ToString();
            }

            var list = _orderBll.GetList().OrderByDescending(x => x.OrderId).Take(100).ToList().Select(x => x.OrderId).ToArray();
            this.cmbOrderId.Items.AddRange(list);
        }

        private void cmbOrderId_SelectedIndexChanged(object sender, EventArgs e)
        {
            ChangeValue();
        }

        private void cmbOrderId_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                ChangeValue();
            }
        }
        public void ChangeValue()
        {
            if (!string.IsNullOrEmpty(cmbOrderId.Text))
            {
                var list = _orderBll.GetListByWhere(cmbOrderId.Text).ToList();
                if (list == null || list.Count < 1)
                {
                    MessageBox.Show("该制令单号不存在!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                OrderEntity orderEntity = list[0];
                this.txtBatch.Text = orderEntity.Batch;
                this.txtFinishedProductName.Text = orderEntity.FinishedProductName;
                this.cmbLineType.Text = orderEntity.LineType;
                this.txtJuanNum.Text = orderEntity.JuanNum;
                this.cmbOperator.Text = orderEntity.Operator;
            }
        }

        private void btnSaveAndPrint_Click(object sender, EventArgs e)
        {
            if (!IsValid())
                return;
            var list = _orderBll.GetListByWhere(cmbOrderId.Text).ToList();
            if (list == null || list.Count < 1)
            {
                MessageBox.Show("该制令单号不存在!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            var entity = GetEntity();
            printEntity = GetEntity();

            var tempBoxNum = entity.BoxNum ;

            //将箱号从“至”转换成逗号分隔
            if (entity.BoxNum.Contains("至"))
            {
                string boxnum = "";
                var sumList = entity.BoxNum.Split("至").ToList();
                int begin = Convert.ToInt32(sumList[0].Substring(4));
                int end = Convert.ToInt32(sumList[1].Substring(4));
                for (int i = begin; i <= end; i++)
                {
                    boxnum += DateTime.Now.Year.ToString() + i + "-";
                }
                boxnum = boxnum.Remove(boxnum.Length - 1, 1);
                entity.BoxNum = boxnum;
            }
            var flag = boxNumBLL.Insert(entity);
            if (flag)
            {
                //更新箱号
                var changeEntity = changefulBLL.GetList().ToList();
                if (changeEntity != null && changeEntity.Count == 1)
                {
                    var entityEx = changeEntity[0];
                    entityEx.BoxNum = boxnum;
                    var flag1 = changefulBLL.Update(entityEx);
                    if (flag1)
                    {
                        //更新页面的箱号并开始打印
                        initboxnum = boxnum + 1;
                        boxnum = initboxnum;
                        this.txtBoxNum.Text = DateTime.Now.Year.ToString() + boxnum.ToString();
                        //numBoxCount.Value = numBoxCount.Value;
                        numBoxCount.Value = 1;
                        string sum = tempBoxNum;
                        if (sum.Contains("至"))
                        {
                            var sumList = sum.Split("至").ToList();
                            int begin = Convert.ToInt32(sumList[0].Substring(4));
                            int end = Convert.ToInt32(sumList[1].Substring(4));
                            for (int i = begin; i <= end; i++)
                            {
                                printBox.Add( DateTime.Now.Year.ToString() + i);
                                //Print();
                            }
                        }
                        else
                        {
                            printBox.Add(sum);
                            //Print();
                        }
                        Print();
                        MessageBox.Show("打印已完成!", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                //MessageBox.Show("新增成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("新增失败!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            //boxNumBLL
        }
        //打印用的箱号和实体
        List<string> printBox = new List<string>();
        BoxNumEntity printEntity = null;

        public void Print()
        {
            try
            {
                if (IsExist())
                {
                    PrintByIniParam();
                }
                else
                {
                    SetPrinter();
                }
            }
            catch (Exception ex)
            {
                _log.Error(ex.ToString());
            }
        }
        public void SetPrinter()
        {
            PrinterSettingEntity printerSettingEntity = new PrinterSettingEntity();
            PageSetting pageSetting = new PageSetting();
            PrinterSetting printerSetting = new PrinterSetting();
            //先把中变变量设置到控件中
            PageSetupDialog pageSetupDialog1 = new PageSetupDialog();
            pageSetupDialog1.Document = printDocument1;
            pageSetupDialog1.AllowMargins = true;
            pageSetupDialog1.AllowOrientation = true;
            pageSetupDialog1.AllowPaper = true;
            pageSetupDialog1.AllowPrinter = true;
            pageSetupDialog1.ShowHelp = true;
            if (pageSetupDialog1.ShowDialog() == DialogResult.OK)
            {
                printDocument1.DefaultPageSettings = pageSetupDialog1.PageSettings;
                pageSetting.Landscape = printDocument1.DefaultPageSettings.Landscape;

                pageSetting.PaperSize = new Entity.OtherEntity.PaperSize();
                pageSetting.PaperSize.PaperName = printDocument1.DefaultPageSettings.PaperSize.PaperName;
                pageSetting.PaperSize.RawKind = printDocument1.DefaultPageSettings.PaperSize.RawKind;
                pageSetting.PaperSize.Width = printDocument1.DefaultPageSettings.PaperSize.Width;
                pageSetting.PaperSize.Height = printDocument1.DefaultPageSettings.PaperSize.Height;
                pageSetting.PaperSize.Kind = (int)printDocument1.DefaultPageSettings.PaperSize.Kind;

                pageSetting.Margin = new Margin();
                pageSetting.Margin.Top = printDocument1.DefaultPageSettings.Margins.Top;
                pageSetting.Margin.Bottom = printDocument1.DefaultPageSettings.Margins.Bottom;
                pageSetting.Margin.Left = printDocument1.DefaultPageSettings.Margins.Left;
                pageSetting.Margin.Right = printDocument1.DefaultPageSettings.Margins.Right;
                //printDocument1.DefaultPageSettings.Margins;
                printerSettingEntity.pageSetting = pageSetting;
            }
            else
                return;

            PrintDialog print = new PrintDialog();
            print.Document = printDocument1;
            print.AllowCurrentPage = true;
            print.AllowPrintToFile = true;
            print.AllowSelection = true;
            print.AllowSomePages = true;
            print.ShowHelp = true;
            if (print.ShowDialog() == DialogResult.OK)
            {
                printDocument1.PrinterSettings = print.PrinterSettings;
                printerSetting.PrinterName = printDocument1.PrinterSettings.PrinterName;
                printerSettingEntity.printerSetting = printerSetting;
            }
            else
                return;
            iniConfig.Write("Landscape", printerSettingEntity.pageSetting.Landscape == true ? "True" : "False", "BoxPrinter");
            iniConfig.Write("Top", printerSettingEntity.pageSetting.Margin.Top.ToString(), "BoxPrinter");
            iniConfig.Write("Bottom", printerSettingEntity.pageSetting.Margin.Bottom.ToString(), "BoxPrinter");
            iniConfig.Write("Left", printerSettingEntity.pageSetting.Margin.Left.ToString(), "BoxPrinter");
            iniConfig.Write("Right", printerSettingEntity.pageSetting.Margin.Right.ToString(), "BoxPrinter");
            iniConfig.Write("PrinterName", printerSettingEntity.printerSetting.PrinterName, "BoxPrinter");

            iniConfig.Write("PaperName", printerSettingEntity.pageSetting.PaperSize.PaperName, "BoxPrinter");
            iniConfig.Write("RawKind", printerSettingEntity.pageSetting.PaperSize.RawKind.ToString(), "BoxPrinter");
            iniConfig.Write("Width", printerSettingEntity.pageSetting.PaperSize.Width.ToString(), "BoxPrinter");
            iniConfig.Write("Height", printerSettingEntity.pageSetting.PaperSize.Height.ToString(), "BoxPrinter");
            //打印的是中间变量
            printDocument1.Print();
        }
        public void PrintByIniParam()
        {
            printDocument1.DefaultPageSettings.Landscape = Convert.ToBoolean(iniConfig.Read("Landscape", "BoxPrinter"));
            printDocument1.DefaultPageSettings.Margins.Right = Convert.ToInt32(iniConfig.Read("Right", "BoxPrinter"));
            printDocument1.DefaultPageSettings.Margins.Left = Convert.ToInt32(iniConfig.Read("Left", "BoxPrinter"));
            printDocument1.DefaultPageSettings.Margins.Top = Convert.ToInt32(iniConfig.Read("Top", "BoxPrinter"));
            printDocument1.DefaultPageSettings.Margins.Bottom = Convert.ToInt32(iniConfig.Read("Bottom", "BoxPrinter"));


            printDocument1.PrinterSettings.PrinterName = iniConfig.Read("PrinterName", "BoxPrinter");

            printDocument1.DefaultPageSettings.PaperSize = new System.Drawing.Printing.PaperSize(iniConfig.Read("PaperName", "BoxPrinter"), Convert.ToInt32(iniConfig.Read("Width", "BoxPrinter")), Convert.ToInt32(iniConfig.Read("Height", "BoxPrinter")));

            printDocument1.Print();
        }
        public bool IsValid()
        {
            errorProvider1.Clear();
            bool res = true;

            if (string.IsNullOrEmpty(cmbOrderId.Text.Trim()))
            {
                res = false;
                errorProvider1.SetError(cmbOrderId, "制令单号不能为空！");
            }
            else if (string.IsNullOrEmpty(txtFinishedProductName.Text.Trim()))
            {
                res = false;
                errorProvider1.SetError(txtFinishedProductName, "成品名称不能为空！");
            }
            else if (string.IsNullOrEmpty(txtBatch.Text.Trim()))
            {
                res = false;
                errorProvider1.SetError(txtBatch, "批号不能为空！");
            }
            else if (string.IsNullOrEmpty(cmbLineType.Text))
            {
                res = false;
                errorProvider1.SetError(cmbLineType, "线型不能为空！");
            }
            else if (string.IsNullOrEmpty(txtJuanNum.Text))
            {
                res = false;
                errorProvider1.SetError(txtJuanNum, "卷号不能为空！");
            }
            else if (string.IsNullOrEmpty(txtStore.Text))
            {
                res = false;
                errorProvider1.SetError(txtStore, "库位不能为空！");
            }
            //else if (!numBoxCount.Value.ToString().Contains("至"))
            //{
            //    res = false;
            //    errorProvider1.SetError(numBoxCount, "需修改箱号！");
            //}
            return res;
        }
        public BoxNumEntity GetEntity()
        {
            BoxNumEntity boxNumEntity = new BoxNumEntity();
            boxNumEntity.Id = Guid.NewGuid().ToString();
            boxNumEntity.OrderId = cmbOrderId.Text;
            boxNumEntity.Batch = txtBatch.Text;
            boxNumEntity.Operator = cmbOperator.Text;
            boxNumEntity.FinishedProductName = txtFinishedProductName.Text;
            boxNumEntity.CreateTime = DateTime.Now;
            boxNumEntity.LineType = cmbLineType.Text;
            boxNumEntity.JuanNum = txtJuanNum.Text;
            boxNumEntity.MaoZhong = numMaoZhong.Value.ToString();
            boxNumEntity.OneBoxCount = Convert.ToInt32(numOneBoxCount.Value);
            boxNumEntity.Store = txtStore.Text;
            boxNumEntity.AllCount = Convert.ToInt32(txtAllBoxCount.Text);
            boxNumEntity.BoxNum = txtBoxNum.Text;
            return boxNumEntity;
        }

        /// <summary>
        /// 判断打印机参数是否正确填写
        /// </summary>
        /// <returns></returns>
        public bool IsExist()
        {
            var flag = iniConfig.KeyExists("Landscape", "BoxPrinter");
            if (!flag)
                return false;
            flag = iniConfig.KeyExists("PrinterName", "BoxPrinter");
            if (!flag)
                return false;
            flag = iniConfig.KeyExists("Top", "BoxPrinter");
            if (!flag)
                return false;
            flag = iniConfig.KeyExists("Bottom", "BoxPrinter");
            if (!flag)
                return false;
            flag = iniConfig.KeyExists("Left", "BoxPrinter");
            if (!flag)
                return false;
            flag = iniConfig.KeyExists("Right", "BoxPrinter");
            if (!flag)
                return false;
            flag = iniConfig.KeyExists("PaperName", "BoxPrinter");
            if (!flag)
                return false;
            flag = iniConfig.KeyExists("RawKind", "BoxPrinter");
            if (!flag)
                return false;
            flag = iniConfig.KeyExists("Width", "BoxPrinter");
            if (!flag)
                return false;
            flag = iniConfig.KeyExists("Height", "BoxPrinter");
            if (!flag)
                return false;
            return true;
        }

        private void PrintBoxNumForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (iniConfig != null)
            {
                iniConfig.Dispose();
                iniConfig = null;
            }
        }

        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            PictureBox pictureBox1 = new PictureBox();
            pictureBox1.Width = 254;
            pictureBox1.Height = 45;
            pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
            using (Barcode barcode = new Barcode())
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    barcode.LabelFont = new SKFont(SKTypeface.FromFamilyName("微软雅黑", SKFontStyle.Bold), 10, 1, 0);
                    barcode.IncludeLabel = true;
                    //barcode.IncludeLabel = false;
                    barcode.Alignment = AlignmentPositions.Center;
                    var barcodeImage = barcode.Encode(BarcodeStandard.Type.Code128, printBox[0], new SKColor(0, 0, 0, 255), new SKColor(240, 240, 240), 254, 45);
                    var aa = Image.FromStream(barcodeImage.Encode().AsStream());
                    pictureBox1.Image = aa;
                }
            }
            PictureBox pictureBox2 = new PictureBox();
            pictureBox2.Width = 254;
            pictureBox2.Height = 45;
            pictureBox2.SizeMode = PictureBoxSizeMode.StretchImage;
            using (Barcode barcode = new Barcode())
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    barcode.LabelFont = new SKFont(SKTypeface.FromFamilyName("微软雅黑",SKFontStyle.Bold), 10, 1, 0);
                    barcode.IncludeLabel = true;
                    //barcode.IncludeLabel = false;
                    barcode.Alignment = AlignmentPositions.Center;
                    var barcodeImage = barcode.Encode(BarcodeStandard.Type.Code128, printEntity.Store, new SKColor(0, 0, 0, 255), new SKColor(240, 240, 240), 254, 45);
                    var aa = Image.FromStream(barcodeImage.Encode().AsStream());
                    pictureBox2.Image = aa;
                }
            }

            e.Graphics.DrawString("PART NUM", new Font(new FontFamily("微软雅黑"), 10, FontStyle.Bold), System.Drawing.Brushes.Black, 25, 15);
            e.Graphics.DrawString("N-FF13A204A", new Font(new FontFamily("微软雅黑"), 10, FontStyle.Bold), System.Drawing.Brushes.Black, 250, 15);

            e.Graphics.DrawString("PACKAGE NUM", new Font(new FontFamily("微软雅黑"), 10, FontStyle.Bold), System.Drawing.Brushes.Black, 25, 50);
            e.Graphics.DrawImage(pictureBox1.Image, 150, 45);

            e.Graphics.DrawString("PACKAGE TYPE      BOX", new Font(new FontFamily("微软雅黑"), 10, FontStyle.Bold), System.Drawing.Brushes.Black, 25, 100);

            e.Graphics.DrawString(string.Format("SHOP ORDER         {0}       LOT NUMBER {1}", printEntity.OrderId, printEntity.Batch), new Font(new FontFamily("微软雅黑"), 10, FontStyle.Bold), System.Drawing.Brushes.Black, 25, 125);

            e.Graphics.DrawString("STOCK LOC", new Font(new FontFamily("微软雅黑"), 10, FontStyle.Bold), System.Drawing.Brushes.Black, 25, 170);
            e.Graphics.DrawImage(pictureBox2.Image, 150, 160);

            e.Graphics.DrawString(string.Format("QUANTITY             {0}              EA", printEntity.AllCount), new Font(new FontFamily("微软雅黑"), 10, FontStyle.Bold), System.Drawing.Brushes.Black, 25, 210);

            e.Graphics.DrawString(string.Format("REFERENCE            {0}           GROSS WT {1} (KG)",printEntity.JuanNum, printEntity.MaoZhong), new Font(new FontFamily("微软雅黑"), 10, FontStyle.Bold), System.Drawing.Brushes.Black, 25, 230);

            e.Graphics.DrawString(string.Format("RECELIVED BY        {0}        068       CIMC94", printEntity.Operator), new Font(new FontFamily("微软雅黑"), 10, FontStyle.Bold), System.Drawing.Brushes.Black, 25, 250);

            //e.Graphics.DrawString("PACKAGE TYPE  BOX1 \r\n BHOP ORDER M0230511004", new Font(new FontFamily("微软雅黑"), 16, FontStyle.Bold), System.Drawing.Brushes.Black, 15, 15);
            printBox.RemoveAt(0);
            e.HasMorePages = printBox.Count > 0 ? true:false;

        }

        private void printDocument1_EndPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
        {
            
        }
    }
}
